<template>
  <div style="width: 100%">
    <div class="tabs-con">
      <el-collapse v-model="collapse">
        <template v-for="(item,index) in groupList">
          <el-collapse-item :name="index">
            <template slot="title">
              <div class="collapse-header">
                <span>分组：</span>
                <el-input @click.native.stop @input.stop.prevent size="mini" v-model.trim="item.nameCn"></el-input>
                &nbsp;&nbsp;
                <el-button size="mini" type="text" icon="el-icon-delete" @click="delGroup(index)"></el-button>
              </div>
            </template>

            <div>
              <el-button size="mini" type="text" icon="el-icon-plus" @click="addAttr(index)">添加属性</el-button>
            </div>
            <draggable :list="item.attributeList" tag="div" class="divGroup"
                       :group="{name: 'dragGroup',pull:true, put: true}">
              <div class="divItem" v-for="(cItem,cIndex) in item.attributeList">
                <div class="label drag-option">属性：</div>
                <el-select size="mini" clearable filterable v-model="cItem.attributeName">
                  <template v-for="{label,value} in attributeNameList">
                    <el-option :label="label" :value="value" :disabled="disabledOption.includes(value)"></el-option>
                  </template>
                </el-select>
                &nbsp;
                <el-popover
                    placement="top"
                    width="400"
                    trigger="click">
                  <div>请参考AVUE
                    <el-link target="_blank"
                             href="https://avuejs.com/form/form-doc.html#column-%E5%85%B1%E7%94%A8%E5%B1%9E%E6%80%A7">
                      column属性
                    </el-link>
                  </div>
                  <p></p>
                  <el-input size="small" type="textarea" :rows="5" resize="none"
                            v-model="cItem.attributeJson" placeholder="请输入属性JSON……"></el-input>

                  <el-button size="mini" :type="!!cItem.attributeJson?'primary':''" slot="reference">json</el-button>
                </el-popover>
                &nbsp;&nbsp;&nbsp;
                <el-button size="mini" type="text" icon="el-icon-delete" @click="delAttr(index,cIndex)"></el-button>
              </div>
            </draggable>
          </el-collapse-item>
        </template>
      </el-collapse>
      <p></p>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addGroup">添加分组</el-button>
    </div>

    <div class="md-component-btns">
      <el-button size="medium" type="primary" @click="save">保存</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>
  </div>
</template>
<script>
import Draggable from 'vuedraggable'
import {extends_attribute} from "@/api/modulManage/entity";
import {insertLayout, layoutDetail} from "@/api/quickExtend/quickExtend";
import * as api from "@/api/quickExtend/quickExtend";

export default {
  name: "layoutEditTemp",
  components: {Draggable},
  data() {
    return {
      collapse: [],

      type: "",//1 创建布局 2 编辑布局 3详情布局

      attributeNameList: [],
      groupList: [
        {
          nameCn: "基本属性",
          attributeList: []
        },
        {
          nameCn: "继承属性",
          attributeList: []
        },
        {
          nameCn: "扩展属性",
          attributeList: []
        }
      ],

      submitForm: {
        typeName: "",//模型Id
        type: "",//新增类型
      },

      dialogType: "add",
    }
  },
  computed: {
    disabledOption() {
      let arr = [];
      this.groupList.forEach(item => {
        item.attributeList.forEach(i => {
          arr.push(i.attributeName)
        })
      })

      return arr;
    }
  },
  methods: {
    save() {
      let method = this.dialogType === "add" ? "insertLayout" : "updateLayout";

      let flag = true;
      let con = true;
      let je = false;
      let jsonError = [];
      this.groupList.forEach(item => {
        let error = [];
        if (!item.nameCn) {
          flag = false;
        }
        if (item.attributeList.length > 0) {
          item.attributeList.forEach(i => {
            if (!i.attributeName) {
              con = false;
            }

            if (i.attributeJson && !this.isJSON(i.attributeJson)) {
              error.push(i);
              je = true;
            }
          })
        }

        jsonError.push({group: item.nameCn, error: error})
      })
      if (!flag) {
        this.$message.warning("请输入分组名称");
        return;
      }
      if (!con) {
        this.$message.warning("请选择属性");
        return;
      }
      if (je) {
        let msg = "";
        jsonError.forEach((i) => {
          if (i.error.length > 0) {
            msg += i.group + " [" + i.error.map(c => c.attributeName).join('，') + "] "
          }

        })
        this.$message.warning(msg + " JSON配置错误");
        return;
      }
      api[method]({...this.submitForm, groupList: this.groupList}).then(() => {
        this.$message.success("保存成功");
        this.$emit('refresh');
        this.$emit('removeThisTabs');
      })
    },

    addGroup() {
      this.groupList.push({
        nameCn: "",
        attributeList: []
      })
    },
    delGroup(index) {
      this.groupList.splice(index, 1);
    },

    delAttr(index, cIndex) {
      this.groupList[index].attributeList.splice(cIndex, 1);
    },
    addAttr(index) {
      this.groupList[index].attributeList.push({attributeJson: "", attributeName: ""})
    },
    async open(form) {
      this.submitForm.type = form.layoutType;
      this.submitForm.typeName = form.name;

      let {groupVoList} = await this.showEdit(form);
      let type = this.dialogType = groupVoList.length === 0 ? "add" : "edit";

      this.setAllAtr(form, type, groupVoList);

      if (type === "edit") {
        this.groupList = this.deepCopy(groupVoList);
      }
    },
    // 编辑
    async showEdit(f) {
      const res = await layoutDetail({typeName: f.name, type: f.layoutType});
      return res.data.data;
    },
    // 获取所有的可选属性
    setAllAtr(form, type) {
      let {extendAttributeList} = this.deepCopy(form);
      extendAttributeList.forEach((item) => {
        if (item.columnName) {
          this.attributeNameList.push({label: item.nameCn, value: item.columnName})
          if (type === "add") {
            this.groupList[2].attributeList.push({
              attributeJson: "",
              attributeName: item.columnName
            })
          }
        }
      })

      let name = [];
      if (form.functionInterfaceList && form.functionInterfaceList.length > 0) {
        let n = form.functionInterfaceList.map(i => i.name);
        name.push(...n)
      }
      if (form.businessInterfaceList && form.businessInterfaceList.length > 0) {
        let n = form.businessInterfaceList.map(i => i.name);
        name.push(...n)
      }

      extends_attribute({
        typeName: form.parentName,
        refType: "1",
        interfaceNames: name.join(",")
      }).then(res => {
        let data = res.data.data;
        data.forEach(item => {
          if (item.columnName) {
            this.attributeNameList.push({label: item.nameCn, value: item.columnName})
            if (type === "add") {
              this.groupList[1].attributeList.push({
                attributeJson: "",
                attributeName: item.columnName
              })
            }
          }
        })
      })
    }
  },
  watch: {
    groupList: {
      handler(v) {
        this.collapse = [];
        if (v && v.length > 0) {
          for (let i = 0; i < v.length; i++) {
            this.collapse.push(i)
          }
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
.tabs-con {
  width: 100%;

  .divGroup {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: wrap;

    .divItem {
      width: calc((100% - 20px) / 2);
      height: 26px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      flex-wrap: nowrap;
      margin-bottom: 15px;

      .label {
        width: 120px;
        line-height: 28px;
        text-align: right;
        cursor: move;
      }

      .el-select {
        width: 300px;
      }
    }

    .divItem:nth-child(odd) {
      margin-right: 20px;
    }
  }

  .collapse-header {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: nowrap;
    width: 350px;

    > span {
      display: inline-block;
      width: 90px;
    }
  }
}
</style>
